"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SerialState = void 0;
/// <reference types="dom-serial"/>
/**
 * serial state simple enum
 */
var SerialState;
(function (SerialState) {
    SerialState[SerialState["Uninitial"] = 0] = "Uninitial";
    SerialState[SerialState["Unsupport"] = 1] = "Unsupport";
    SerialState[SerialState["Disconnect"] = 2] = "Disconnect";
    SerialState[SerialState["Connected"] = 3] = "Connected";
})(SerialState = exports.SerialState || (exports.SerialState = {}));
var SerialCommon = /** @class */ (function () {
    function SerialCommon(baudRate) {
        if (baudRate === void 0) { baudRate = 115200; }
        var _this = this;
        this._serial = null;
        this._port = undefined;
        this._ports = [];
        this._reader = null;
        this._writer = null;
        this._readPromise = null;
        this._onmessage = undefined;
        this._onconnect = undefined;
        this._ondisconnect = undefined;
        this._baudRate = baudRate;
        this._state = SerialState.Uninitial;
        if ("serial" in window.navigator == false) {
            this._state = SerialState.Unsupport;
            console.error("Brower is not Support Serial");
        }
        else {
            this._serial = navigator.serial;
            this._serial.onconnect = function () { return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.connect()];
                        case 1:
                            _a.sent();
                            console.debug("onconnect");
                            if (this._onconnect)
                                this._onconnect();
                            return [2 /*return*/];
                    }
                });
            }); };
            this._serial.ondisconnect = function () { return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_a) {
                    this._state = SerialState.Disconnect;
                    console.debug("ondisconnect");
                    if (this._ondisconnect)
                        this._ondisconnect();
                    return [2 /*return*/];
                });
            }); };
        }
    }
    Object.defineProperty(SerialCommon.prototype, "ports", {
        get: function () { return this._ports; },
        enumerable: false,
        configurable: true
    });
    ;
    Object.defineProperty(SerialCommon.prototype, "state", {
        get: function () { return this._state == SerialState.Connected; },
        enumerable: false,
        configurable: true
    });
    ;
    Object.defineProperty(SerialCommon.prototype, "baudRate", {
        set: function (x) { this._baudRate = x; },
        enumerable: false,
        configurable: true
    });
    ;
    Object.defineProperty(SerialCommon.prototype, "onmessage", {
        set: function (x) { this._onmessage = x; },
        enumerable: false,
        configurable: true
    });
    ;
    Object.defineProperty(SerialCommon.prototype, "onconnect", {
        set: function (x) { this._onconnect = x; },
        enumerable: false,
        configurable: true
    });
    ;
    Object.defineProperty(SerialCommon.prototype, "ondisconnect", {
        set: function (x) { this._ondisconnect = x; },
        enumerable: false,
        configurable: true
    });
    ;
    SerialCommon.prototype.request = function (filters) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function () {
            var _c, _d;
            return __generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        _c = this;
                        return [4 /*yield*/, ((_a = this._serial) === null || _a === void 0 ? void 0 : _a.requestPort({ filters: filters }))];
                    case 1:
                        _c._port = _e.sent();
                        _d = this;
                        return [4 /*yield*/, ((_b = this._serial) === null || _b === void 0 ? void 0 : _b.getPorts())];
                    case 2:
                        _d._ports = (_e.sent()) || [];
                        return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 选择已授权的第一个设备进行连接
     * @returns 是否连接成功
     */
    SerialCommon.prototype.connect = function () {
        var _a;
        return __awaiter(this, void 0, void 0, function () {
            var _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        _b = this;
                        return [4 /*yield*/, ((_a = this._serial) === null || _a === void 0 ? void 0 : _a.getPorts())];
                    case 1:
                        _b._ports = (_c.sent()) || [];
                        if (this._ports.length > 0) {
                            this._port = this._ports[0];
                        }
                        else {
                            // await this.request();
                            return [2 /*return*/, false];
                        }
                        return [4 /*yield*/, this.open()];
                    case 2: return [2 /*return*/, _c.sent()];
                }
            });
        });
    };
    /**
     * 选择上一次连接的设备进行连接
     * @returns 是否连接成功
     */
    SerialCommon.prototype.open = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._openSerial()];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * 连接核心实现
     * @returns 是否连接成功
     */
    SerialCommon.prototype._openSerial = function () {
        var _a, _b, _c;
        return __awaiter(this, void 0, void 0, function () {
            var error_1;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _d.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, ((_a = this._port) === null || _a === void 0 ? void 0 : _a.open({ baudRate: this._baudRate }))];
                    case 1:
                        _d.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        error_1 = _d.sent();
                        console.debug(error_1);
                        return [2 /*return*/, false];
                    case 3:
                        this._state = SerialState.Connected;
                        this._reader = (_b = this._port) === null || _b === void 0 ? void 0 : _b.readable.getReader();
                        this._writer = (_c = this._port) === null || _c === void 0 ? void 0 : _c.writable.getWriter();
                        this._readPromise = this._readTask();
                        return [2 /*return*/, true];
                }
            });
        });
    };
    /**
     *
     * @param data 需要写入的数据
     * @returns 是否写入成功
     */
    SerialCommon.prototype.write = function (data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(this._port && this._state == SerialState.Connected)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this._writer.write(data)];
                    case 1:
                        _a.sent();
                        console.debug(data);
                        return [2 /*return*/, true];
                    case 2: return [2 /*return*/, false];
                }
            });
        });
    };
    /**
     * 关闭串口
     * @returns 是否关闭成功
     */
    SerialCommon.prototype.close = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this._closeSerial()];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    /**
     * 关闭核心代码
     * @returns 是否关闭成功
     */
    SerialCommon.prototype._closeSerial = function () {
        var _a, _b, _c;
        return __awaiter(this, void 0, void 0, function () {
            var error_2;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _d.trys.push([0, 4, , 5]);
                        (_a = this._writer) === null || _a === void 0 ? void 0 : _a.releaseLock();
                        return [4 /*yield*/, ((_b = this._reader) === null || _b === void 0 ? void 0 : _b.cancel())];
                    case 1:
                        _d.sent();
                        return [4 /*yield*/, this._readPromise];
                    case 2:
                        _d.sent();
                        return [4 /*yield*/, ((_c = this._port) === null || _c === void 0 ? void 0 : _c.close())];
                    case 3:
                        _d.sent();
                        this._state = SerialState.Disconnect;
                        return [2 /*return*/, true];
                    case 4:
                        error_2 = _d.sent();
                        console.log(error_2);
                        return [2 /*return*/, false];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    /**
     * 读取任务， 读取信息后触发onmessage
     */
    SerialCommon.prototype._readTask = function () {
        return __awaiter(this, void 0, void 0, function () {
            var _a, value, done, error_3;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!(this._port && this._port.readable && this._state == SerialState.Connected)) return [3 /*break*/, 9];
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 6, 7, 8]);
                        _b.label = 2;
                    case 2: return [4 /*yield*/, this._reader.read()];
                    case 3:
                        _a = _b.sent(), value = _a.value, done = _a.done;
                        if (done)
                            return [3 /*break*/, 5];
                        if (this._onmessage) {
                            this._onmessage(value);
                        }
                        _b.label = 4;
                    case 4: return [3 /*break*/, 2];
                    case 5: return [3 /*break*/, 8];
                    case 6:
                        error_3 = _b.sent();
                        console.error(error_3);
                        return [3 /*break*/, 8];
                    case 7:
                        this._reader.releaseLock();
                        this._state = SerialState.Disconnect;
                        return [7 /*endfinally*/];
                    case 8: return [3 /*break*/, 0];
                    case 9: return [2 /*return*/];
                }
            });
        });
    };
    return SerialCommon;
}());
exports.default = {
    SerialCommon: SerialCommon,
    SerialState: SerialState,
};
